/**
 * Copyright (c) Software Institute of PKU
 * All rights reserved. 
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 */
package edu.pku.sei.transformation.editor.controller.editparts.link;

import java.beans.PropertyChangeEvent;

import org.eclipse.draw2d.IFigure;
import org.eclipse.gef.EditPolicy;
import org.eclipse.swt.SWT;

import edu.pku.sei.modeler.edit.parts.AbstractLinkEditPart;
import edu.pku.sei.modeler.model.structure.MetaShapeElement;
import edu.pku.sei.transformation.editor.controller.policies.TransformationtConnetionEditPolicy;
import edu.pku.sei.transformation.editor.model.ModelPackage;
import edu.pku.sei.transformation.editor.model.RuleInvoke;
import edu.pku.sei.transformation.editor.views.figures.ConnectionFigure;
import edu.pku.sei.transformation.editor.views.icons.IconsProvider;

/**
 * @generated
 * 
 */
public class RuleInvokeEditpart extends AbstractLinkEditPart {

	public RuleInvokeEditpart(MetaShapeElement model) {
		super(model);
	}

	protected void createEditPolicies() {
		super.createEditPolicies();
		installEditPolicy(EditPolicy.CONNECTION_ROLE,
				new TransformationtConnetionEditPolicy());
	}

	protected IFigure createFigure() {
		ConnectionFigure conn = new ConnectionFigure(SWT.LINE_DASH);
		RuleInvoke ri = (RuleInvoke) getLink().getModelElement();
		conn.setTargetDecoration(ConnectionFigure.ARROW);
		conn.setLabel("<<" + getRuleInvokeType() + ">>",
				ConnectionFigure.CONNECTION_FIGURE_MIDDLE);
		conn.setLabelIcon(IconsProvider
				.getImage(IconsProvider.LINE_DASH_ARROW_ICO),
				ConnectionFigure.CONNECTION_FIGURE_MIDDLE);

		refreshFigureToolTip(conn, ri);

		return conn;
	}

	protected void handlePropertyChanged(PropertyChangeEvent event) {
		RuleInvoke ri = (RuleInvoke) getLink().getModelElement();
		ConnectionFigure figure = (ConnectionFigure) getFigure();
		if (ModelPackage.__RULE_INVOKE_PARAMETER__.equals(event
				.getPropertyName())) {
			refreshFigureToolTip(figure, ri);
		} else {
			super.handlePropertyChanged(event);
		}
	}

	protected void refreshVisuals() {
		super.refreshVisuals();
	}

	private String getRuleInvokeType() {
		if (((RuleInvoke) this.getLink().getModelElement()).getInvokeType() == RuleInvoke.RULE_PRECONDITION)
			return "precondition";
		else if (((RuleInvoke) this.getLink().getModelElement())
				.getInvokeType() == RuleInvoke.RULE_POSTCONDITION)
			return "postcondition";
		else
			return "error";

	}

	private void refreshFigureToolTip(ConnectionFigure figure, RuleInvoke ri) {
		String s = ri.getCallee().getName() + "(";
		for (int i = 0; i < ri.getParameters().size(); i++) {
			s += ri.getParameters().get(i).toString();
			// if (i != ri.getParameters().size() - 1)
			// s += ",";
		}
		s += ")";
		figure.setTooltipLabel(s);
	}
}
